package ar.com.pragmatia.lanacion;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Vector;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import ar.com.pragmatia.lanacion.app.App;
import ar.com.pragmatia.lanacion.data.Article;
import ar.com.pragmatia.lanacion.data.Client;
import ar.com.pragmatia.lanacion.data.Order;
import ar.com.pragmatia.lanacion.data.OrderDetail;
import ar.com.pragmatia.lanacion.utils.Strings;

public class NewOrderActivity extends LaNacionActivity {

	private TableLayout table;
	private AutoCompleteTextView txtClientAutocomplete;
	private AutoCompleteTextView txtArticleAutocomplete;
	private Order order;
	private Vector<OrderDetail> orderDetails;
	private Button btnAddOrder;
	private float total;
	private Spinner spnDocumentType;
	private Spinner spnOrderType;

	// private LocationListener locationListener;
	private LocationListener locationListener2;
	private LocationManager locationManager;
	private int trys;
	private ProgressDialog progressDialog;

	private Dialog dialog;
	private Context appContext;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.orders_new);

		Button btnClients = (Button) findViewById(R.id.btnOrders);
		if (btnClients != null) {
			btnClients.setPressed(true);
		}

		if (order == null) {
			order = new Order();
		}
		appContext = this;
		orderDetails = new Vector<OrderDetail>();

		table = (TableLayout) findViewById(R.id.tblOrderDetails);
		btnAddOrder = (Button) findViewById(R.id.btnAddOrder);

		spnDocumentType = (Spinner) findViewById(R.id.spnDocumentType);
		spnOrderType = (Spinner) findViewById(R.id.spnOrderType);

		ArrayAdapter<CharSequence> aAAdapter = ArrayAdapter.createFromResource(
				this, R.array.document_type_items_view,
				android.R.layout.simple_spinner_item);
		aAAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnDocumentType.setAdapter(aAAdapter);

		ArrayAdapter<CharSequence> aAAAdapter = ArrayAdapter
				.createFromResource(this, R.array.order_type_items_view,
						android.R.layout.simple_spinner_item);
		aAAAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnOrderType.setAdapter(aAAAdapter);

		txtClientAutocomplete = (AutoCompleteTextView) findViewById(R.id.txtClientAutocomplete);

		ArrayAdapter<Client> aAdapter = new ArrayAdapter<Client>(this,
				R.layout.list_item);
		aAdapter.addAll((Collection) new Client().find());
		txtClientAutocomplete.setAdapter(aAdapter);

		// TravelingLoad tl = new TravelingLoad();
		// Vector<AppData> v = tl.find();
		// App.log("TL", "TS", v.size() + "");
		//
		// Article art = new Article();
		// Vector<AppData> ve = art.find();
		// App.log("TL", "TS", ve.size() + "");

		txtClientAutocomplete.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				Object o = arg0.getItemAtPosition(arg2);
				order.setClientId(((Client) o).getId());
			}

		});

		txtArticleAutocomplete = (AutoCompleteTextView) findViewById(R.id.txtArticleAutocomplete);

		ArrayAdapter<Article> adapter = new ArrayAdapter<Article>(this,
				R.layout.list_item);
		adapter.addAll((Collection) new Article().find());
		txtArticleAutocomplete.setAdapter(adapter);

		txtArticleAutocomplete
				.setOnItemClickListener(new OnItemClickListener() {

					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						Article art = (Article) arg0.getItemAtPosition(arg2);
						for (int i = 0; i < orderDetails.size(); i++) {
							OrderDetail oDetail = orderDetails.get(i);
							if (oDetail.getArticleId() == art.getId()) {
								txtArticleAutocomplete.setText("");
								return;
							}
						}
						OrderDetail detail = new OrderDetail();
						detail.setArticle(art);
						detail.setArticleId(art.getId());
						detail.setQuantity("1");
						detail.setPrice(art.getPrice());
						orderDetails.add(detail);
						updateTable();
						table.getChildAt(table.getChildCount() - 1)
								.performClick();
						txtArticleAutocomplete.setText("");
					}

				});

		btnAddOrder.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (!Strings.isNullOrEmpty(order.getClientId())) {
					locationManager = (LocationManager) appContext
							.getSystemService(Context.LOCATION_SERVICE);
					trys = 0;
					progressDialog = ProgressDialog.show(NewOrderActivity.this,
							getString(R.string.wait),
							getString(R.string.loading), true, false);
					// Define a listener that responds to location updates
					// locationListener = new LocationListener() {
					// public void onLocationChanged(Location location) {
					// // Called when a new location is found by the network
					// // location provider.
					// makeUseOfNewLocation(location);
					// }
					//
					// public void onStatusChanged(String provider, int status,
					// Bundle extras) {
					// }
					//
					// public void onProviderEnabled(String provider) {
					// }
					//
					// public void onProviderDisabled(String provider) {
					// }
					// };
					locationListener2 = new LocationListener() {
						public void onLocationChanged(Location location) {
							// Called when a new location is found by the
							// network
							// location provider.
							makeUseOfNewLocation(location);
						}

						public void onStatusChanged(String provider,
								int status, Bundle extras) {
						}

						public void onProviderEnabled(String provider) {
						}

						public void onProviderDisabled(String provider) {
						}
					};

					// Register the listener with the Location Manager to
					// receive
					// location updates
					// locationManager.requestLocationUpdates(
					// LocationManager.NETWORK_PROVIDER, 300, 0,
					// locationListener);
					locationManager.requestLocationUpdates(
							LocationManager.GPS_PROVIDER, 300, 0,
							locationListener2);

				} else {
					int duration = Toast.LENGTH_SHORT * 2;
					Toast toast = Toast.makeText(appContext,
							getText(R.string.select_client), duration);
					toast.show();
				}
			}
		});

	}

	private void makeUseOfNewLocation(Location l) {
		if (l.getAccuracy() < 10 || trys >= 10) {
			locationManager.removeUpdates(locationListener2);
			progressDialog.dismiss();

			order.setLocation("(" + l.getLatitude() + ", " + l.getLongitude()
					+ ")");
			order.setDocumentType(spnDocumentType.getSelectedItem().toString());
			order.setOrderType(spnOrderType.getSelectedItem().toString());
			order.setSellerId(App.getUser().getId());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			order.setCreated(sdf.format(new Date()));
			if (order.save(true)) {
				String id = order.find("ORDER BY id DESC LIMIT 1").get(0)
						.getId();
				for (int i = 0; i < orderDetails.size(); i++) {
					orderDetails.get(i).setOrderId(id);
					orderDetails.get(i).setCreated(sdf.format(new Date()));
					orderDetails.get(i).save(true);
				}
			}
			Intent intent = new Intent().setClass(appContext,
					MainOrderActivity.class);
			int duration = Toast.LENGTH_SHORT * 2;
			Toast toast = Toast.makeText(appContext,
					getText(R.string.order_added), duration);
			toast.show();
			startActivity(intent);
		}
		trys++;
	}

	private void addTableHeader() {
		TableRow row = new TableRow(this);

		TextView c = new TextView(this);
		c.setText(getText(R.string.code));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		c = new TextView(this);
		c.setText(getText(R.string.name));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		c = new TextView(this);
		c.setText(getText(R.string.quantity));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		c = new TextView(this);
		c.setText(getText(R.string.price));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		c = new TextView(this);
		c.setText(getText(R.string.subtotal));
		c.setPadding(3, 3, 3, 3);
		row.addView(c);

		row.setBackgroundColor(0xEEEEEEEE);

		table.addView(row, new TableLayout.LayoutParams());
	}

	private void updateTable() {
		table.removeAllViews();
		addTableHeader();
		appendRows(orderDetails);
	}

	private void appendRows(Vector<OrderDetail> clients) {
		int rowSize = clients.size();
		total = 0;
		for (int i = 0; i < rowSize; i++) {
			TableRow row = new TableRow(this);

			TextView c = new TextView(this);

			c = new TextView(this);
			c.setText(((Article) clients.get(i).getArticle()).getCode());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			c = new TextView(this);
			c.setText(((Article) clients.get(i).getArticle()).getName());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			c = new TextView(this);
			c.setText(((OrderDetail) clients.get(i)).getQuantity());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			c = new TextView(this);
			c.setText(((OrderDetail) clients.get(i)).getPrice());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			float subtotal = (new Float(
					((OrderDetail) clients.get(i)).getPrice())).floatValue()
					* new Integer(((OrderDetail) clients.get(i)).getQuantity())
							.intValue();

			c = new TextView(this);
			c.setText(new Float(subtotal).toString());
			c.setPadding(3, 3, 3, 3);
			row.addView(c);

			row.setTag(i);

			total += subtotal;

			row.setOnClickListener(new OnClickListener() {

				public void onClick(final View v) {
					// v.getTag();

					dialog = new Dialog(appContext);
					dialog.setContentView(R.layout.dialog_quantity);

					final OrderDetail ord = orderDetails.get(new Integer(v
							.getTag().toString()).intValue());

					dialog.setTitle("");
					final EditText txtShopName = (EditText) dialog
							.findViewById(R.id.txtQuantity);

					if (ord != null) {
						dialog.setTitle(ord.getArticle().getName());

						txtShopName.setText(ord.getQuantity());

					}

					Button cancel = (Button) dialog
							.findViewById(R.id.btnCancel);
					cancel.setOnClickListener(new OnClickListener() {

						public void onClick(View v) {
							dialog.dismiss();

						}
					});
					Button save = (Button) dialog.findViewById(R.id.btnSave);
					save.setOnClickListener(new OnClickListener() {

						public void onClick(View v) {
							ord.setQuantity(txtShopName.getText().toString());
							updateTable();
							dialog.dismiss();

						}
					});
					Button delete = (Button) dialog
							.findViewById(R.id.btnDelete);
					delete.setOnClickListener(new OnClickListener() {

						public void onClick(View vi) {
							orderDetails.remove(new Integer(v.getTag()
									.toString()).intValue());
							updateTable();
							dialog.dismiss();

						}
					});

					dialog.show();
					txtShopName.setSelection(txtShopName.getText().length());
				}
			});
			TextView txtTotal = (TextView) findViewById(R.id.txtTotal);
			txtTotal.setText(new Float(total).toString());
			table.addView(row, new TableLayout.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.FILL_PARENT, 1.0f));
		}
	}
}
